<template>
  <div class="login-page">
    <!-- 左侧图片区 -->
    <div class="login-left">
      <div class="login-img">
        <!-- 这里可以放logo或图片，建议用img标签替换icon -->
        <i class="el-icon-picture-outline"></i>
      </div>
    </div>
    <!-- 右侧表单区 -->
    <div class="login-right">
      <div class="login-title">互联网医院医院管理系统</div>
      <!-- 只在非忘记密码时显示tab -->
      <div v-if="loginType!=='forgot'" class="login-tabs">
        <span :class="{active: loginType==='account'}" @click="switchTab('account')">账号密码登录</span>
        <span :class="{active: loginType==='mobile'}" @click="switchTab('mobile')">手机验证码登录</span>
      </div>
      <div v-if="loginType==='forgot'" class="forgot-title">忘记密码</div>

      <!-- 账号密码登录表单 -->
      <el-form v-if="loginType==='account'" ref="login" :model="dataForm" :rules="rules" class="login-form" label-width="0px" autocomplete="off">
        <el-form-item prop="username">
          <el-input v-model="dataForm.username" placeholder="请输入账号" prefix-icon="el-icon-user" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="dataForm.password" placeholder="请输入密码" prefix-icon="el-icon-lock" show-password autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="captcha" class="captcha-item">
          <div class="captcha-row">
            <el-input v-model="dataForm.captcha" placeholder="请输入验证码" prefix-icon="el-icon-lock" class="captcha-input" autocomplete="off"></el-input>
            <span class="captcha-img" @click="changeCaptcha">{{ captchaDisplay() }}</span>
            <span class="forget-pwd" @click="switchTab('forgot')">忘记密码?</span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="submitForm()">登录</el-button>
        </el-form-item>
      </el-form>
      <!-- 手机验证码登录表单 -->
      <el-form v-if="loginType==='mobile'" ref="mobileForm" :model="mobileForm" :rules="mobileRules" class="login-form" label-width="0px" autocomplete="off">
        <el-form-item prop="mobile">
          <el-input v-model="mobileForm.mobile" placeholder="请输入手机号" prefix-icon="el-icon-user" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="smsCode">
          <div class="mobile-row">
            <el-input v-model="mobileForm.smsCode" placeholder="请输入验证码" prefix-icon="el-icon-lock" class="mobile-input" autocomplete="off"></el-input>
            <el-button class="get-sms-btn" @click="getSmsCode" :disabled="smsBtnDisabled">{{ smsBtnText }}</el-button>
          </div>
        </el-form-item>
        <el-form-item prop="imgCode" class="captcha-item">
          <div class="captcha-row">
            <el-input v-model="mobileForm.imgCode" placeholder="请输入图片验证码" prefix-icon="el-icon-lock" class="captcha-input" autocomplete="off"></el-input>
            <span class="captcha-img" @click="changeCaptcha">{{ captchaDisplay() }}</span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="submitMobileForm">登录</el-button>
        </el-form-item>
      </el-form>
      <!-- 忘记密码表单 -->
      <el-form v-if="loginType==='forgot'" ref="forgotForm" :model="forgotForm" :rules="forgotRules" class="login-form" label-width="0px" autocomplete="off">
        <el-form-item prop="mobile">
          <el-input v-model="forgotForm.mobile" placeholder="请输入账号" prefix-icon="el-icon-user" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="smsCode">
          <div class="mobile-row">
            <el-input v-model="forgotForm.smsCode" placeholder="请输入验证码" prefix-icon="el-icon-lock" class="mobile-input" autocomplete="off"></el-input>
            <el-button class="get-sms-btn" @click="getForgotSmsCode" :disabled="smsBtnDisabled">{{ smsBtnText }}</el-button>
          </div>
        </el-form-item>
        <el-form-item prop="newPwd">
          <el-input v-model="forgotForm.newPwd" placeholder="请输入新密码" prefix-icon="el-icon-lock" show-password autocomplete="off"></el-input>
        </el-form-item>
        <div v-if="loginType==='forgot'" class="forgot-header">
          <span class="back-login" @click="switchTab('account')">
            ← 返回账号密码登录
          </span>
        </div>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="submitForgot">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import qs from 'qs';

export default {
  data() {
    return {
      loginType: 'account',
      dataForm: {
        username: "",
        password: "",
        captcha: ""
      },
      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      captchaText: this.randomCaptcha(),
      realUser: 'root',
      realPwd: 'root',
      mobileForm: {
        mobile: '',
        smsCode: '',
        imgCode: ''
      },
      mobileRules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }
        ],
        smsCode: [{ required: true, message: "请输入短信验证码", trigger: "blur" }],
        imgCode: [{ required: true, message: "请输入图片验证码", trigger: "blur" }]
      },
      smsBtnText: '获取验证码',
      smsBtnDisabled: false,
      smsTimer: null,
      smsCount: 60,
      forgotForm: {
        mobile: '',
        smsCode: '',
        newPwd: ''
      },
      forgotRules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }
        ],
        smsCode: [{ required: true, message: "请输入短信验证码", trigger: "blur" }],
        newPwd: [{ required: true, message: "请输入新密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    randomCaptcha() {
      const chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
      let str = '';
      for (let i = 0; i < 4; i++) {
        str += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return str;
    },
    changeCaptcha() {
      this.captchaText = this.randomCaptcha();
    },
    captchaDisplay() {
      return this.captchaText.split('').join(' ');
    },
    submitForm() {
      this.$refs.login.validate((valid) => {
        if (valid) {
          if (
            this.dataForm.captcha.trim().toLowerCase() !==
            this.captchaText.toLowerCase()
          ) {
            this.$message.error('验证码错误');
            this.changeCaptcha();
            this.dataForm.captcha = '';
            return;
          }
          // 调用后端登录接口
          axios.post('/user/login', qs.stringify({
            username: this.dataForm.username,
            password: this.dataForm.password
          }), {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success('登录成功');
              sessionStorage.setItem('loginUser', '1');
              setTimeout(() => {
                this.$router.push('/');
              }, 1000);
            } else {
              this.$message.error(res.data.msg || '账号或密码错误');
              this.changeCaptcha();
              this.dataForm.captcha = '';
            }
          }).catch(() => {
            this.$message.error('登录请求失败');
            this.changeCaptcha();
            this.dataForm.captcha = '';
          });
        }
      });
    },
    logout() {
      sessionStorage.removeItem('loginUser');
      this.$router.push('/login');
    },
    getSmsCode() {
      if (!/^1[3-9]\d{9}$/.test(this.mobileForm.mobile)) {
        this.$message.error('请输入正确的手机号');
        return;
      }
      // 调用后端发送验证码接口
      axios.post('user/sendCode', null, {
        params: {
          phone: this.mobileForm.mobile
        }
      }).then(res => {
        if (res.data && res.data.code === 200) {
          this.$message.success('验证码已发送');
          // 启动倒计时
          this.smsBtnDisabled = true;
          this.smsBtnText = `${this.smsCount}s`;
          this.smsTimer = setInterval(() => {
            this.smsCount--;
            this.smsBtnText = `${this.smsCount}s`;
            if (this.smsCount === 0) {
              clearInterval(this.smsTimer);
              this.smsBtnText = '获取验证码';
              this.smsBtnDisabled = false;
              this.smsCount = 60;
            }
          }, 1000);
        } else {
          this.$message.error(res.data.msg || '验证码发送失败');
        }
      }).catch(() => {
        this.$message.error('验证码请求失败');
      });
    },
    submitMobileForm() {
      this.$refs.mobileForm.validate((valid) => {
        if (valid) {
          if (this.mobileForm.imgCode.trim().toLowerCase() !== this.captchaText.toLowerCase()) {
            this.$message.error('图片验证码错误');
            this.changeCaptcha();
            this.mobileForm.imgCode = '';
            return;
          }
          // 这里调用后端接口
          axios.post('user/loginByPhone', null, {
            params: {
              phone: this.mobileForm.mobile,
              code: this.mobileForm.smsCode
            }
          }).then(res => {
            if (res.data && res.data.msg === '登录成功') {
              this.$message.success('登录成功');
              sessionStorage.setItem('loginUser', '1');
              setTimeout(() => {
                this.$router.push('/');
              }, 1000);
            } else {
              this.$message.error(res.data.msg || '登录失败');
            }
          }).catch(() => {
            this.$message.error('请求失败');
          });
        }
      });
    },
    switchTab(type) {
      this.loginType = type;
      if (type === 'mobile') {
        this.changeCaptcha();
        this.mobileForm.imgCode = '';
      }
      if (type === 'account') {
        this.changeCaptcha();
        this.dataForm.captcha = '';
      }
      if (type === 'forgot') {
        this.forgotForm.mobile = '';
        this.forgotForm.smsCode = '';
        this.forgotForm.newPwd = '';
        this.smsBtnText = '获取验证码';
        this.smsBtnDisabled = false;
        if (this.smsTimer) clearInterval(this.smsTimer);
      }
    },
    getForgotSmsCode() {
      if (!/^1[3-9]\d{9}$/.test(this.forgotForm.mobile)) {
        this.$message.error('请输入正确的手机号');
        return;
      }
      // 调用后端发送验证码接口
      axios.post('user/sendCode', null, {
        params: {
          phone: this.forgotForm.mobile
        }
      }).then(res => {
        if (res.data && res.data.code === 200) {
          this.$message.success('验证码已发送');
          this.smsBtnDisabled = true;
          this.smsBtnText = `${this.smsCount}s`;
          this.smsTimer = setInterval(() => {
            this.smsCount--;
            this.smsBtnText = `${this.smsCount}s`;
            if (this.smsCount === 0) {
              clearInterval(this.smsTimer);
              this.smsBtnText = '获取验证码';
              this.smsBtnDisabled = false;
              this.smsCount = 60;
            }
          }, 1000);
        } else {
          this.$message.error(res.data.msg || '验证码发送失败');
        }
      }).catch(() => {
        this.$message.error('验证码请求失败');
      });
    },
    submitForgot() {
      this.$refs.forgotForm.validate((valid) => {
        if (valid) {
          // 调用后端重置密码接口
          axios.post('/user/forgotPassword', {
            phone: this.forgotForm.mobile,
            code: this.forgotForm.smsCode,
            newPassword: this.forgotForm.newPwd
          }).then(res => {
            if (res.data && res.data.code === 200) {
              this.$message.success('密码重置成功，请重新登录');
              this.switchTab('account');
            } else {
              this.$message.error(res.data.msg || '密码重置失败');
            }
          }).catch(() => {
            this.$message.error('请求失败');
          });
        }
      });
    }
  },
  mounted() {
    if (sessionStorage.getItem('loginUser')) {
      this.$router.replace('/dashboard');
    }
  }
};
</script>

<style scoped>
.login-page {
  display: flex;
  height: 100vh;
  background: #fff;
}
.login-left {
  width: 40%;
  background: #393b47;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-img {
  width: 120px;
  height: 120px;
  background: #fff;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 64px;
  color: #393b47;
}
.login-right {
  width: 60%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fff;
}
.login-title {
  font-size: 28px;
  font-weight: bold;
  color: #6d6e76;
  text-align: center;
  margin-bottom: 32px;
  letter-spacing: 2px;
}
.login-tabs {
  width: 350px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 24px;
  border-bottom: 1px solid #e5e5e5;
  position: relative;
}
.login-tabs span {
  font-size: 16px;
  color: #a0a0a0;
  padding: 0 32px 12px 0;
  cursor: pointer;
  position: relative;
  font-weight: 500;
}
.login-tabs .active {
  color: #393b47;
  font-weight: bold;
  border-bottom: 2px solid #393b47;
}
.login-tabs span + span {
  margin-left: 24px;
}
.login-form {
  width: 350px;
  margin-top: 8px;
}
.el-form-item {
  margin-bottom: 24px;
}
.captcha-item {
  margin-bottom: 24px;
}
.captcha-row {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
}
.captcha-input {
  width: 60px;
  flex: 1;
}
.captcha-img {
  min-width: 100px;
  height: 40px;
  background: #3bb397;
  color: #fff;
  border-radius: 4px;
  font-size: 18px;
  letter-spacing: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 12px;
  user-select: none;
  border: 1px solid #dcdfe6;
  border-left: none;
  overflow: hidden;
  padding: 0 10px;
  box-sizing: border-box;
}
.forget-pwd {
  margin-left: auto;
  color: #888;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
  padding-left: 16px;
}
.login-btn {
  width: 100%;
  height: 44px;
  font-size: 18px;
  background: #393b47;
  border: none;
  border-radius: 4px;
  margin-top: 8px;
}
.mobile-row {
  display: flex;
  align-items: center;
}
.mobile-input {
  flex: 1;
}
.get-sms-btn {
  margin-left: 12px;
  min-width: 100px;
  height: 40px;
  background: #393b47;
  color: #fff;
  border: none;
  border-radius: 4px;
}
.forgot-title {
  font-size: 20px;
  font-weight: bold;
  color: #393b47;
  text-align: center;
  margin-bottom: 24px;
  letter-spacing: 2px;
  border-bottom: 1px solid #e5e5e5;
  width: 350px;
  padding-bottom: 12px;
}
.forgot-header {
  width: 350px;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 4px;
}
.back-login {
  color: #393b47;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
}
.back-login:hover {
  color: #409EFF;
  text-decoration: underline;
}
</style>
